<?php
	if (!class_exists('ctl_gallery'))
	{
		require_once(CORE_DIR.'/shop/controller/ctl.gallery.php');
	}

	class diamond_shop_cct_gallery extends ctl_gallery
	{
		function index($view,$cat_id='',$urlFilter=null,$orderBy=0,$tab=null,$page=1,$cat_type=null)
		{
			//error_log(print_r(func_get_args(),true),3,__FILE__.'.'.__FUNCTION__.'.func_get_args.log');//alone add
			/* alone add start */
			$objDiamondCat = &$this->system->loadModel('plugins/diamond/diamondCat');
			$aDisabledCat = $objDiamondCat->getDisabledCat();
			
			if ($cat_id && '_ANY_'!=$cat_id)
			{
				if (is_numeric($cat_id))
				{
					if (in_array($cat_id,$aDisabledCat))
					{
						$this->splash('failed',$this->system->base_url(),'该分类不存在');
					}
					else
					{
						$diamond_tpl_cat = $this->system->getConf('diamond.diamond_cat_tpl');
						if ($cat_id == $diamond_tpl_cat)
						{
							$customView = true;
							$this->pagedata['customView'] = $customView;
						}
					}
				}
				else
				{
					$tmpCat = explode(',',$cat_id);
					foreach ($tmpCat as $k => $v)
					{
						if (in_array($v,$aDisabledCat))
						{
							unset($tmpCat[$k]);
						}
					}
					if (empty($tmpCat))
					{
						$this->splash('failed',$this->system->base_url(),'该分类不存在');
					}
					else $cat_id = implode(',',$tmpCat);
				}
			}
			else
			{
				$enabledCat = $objDiamondCat->getDisabledCat(false);
				$cat_id = implode(',',$enabledCat);
			}
			/* alone add end */

			if($orderBy==5 || $orderBy==6){
				$this->noCache = true;
			}
			if($cat_type){
				$this->type='virtualcat';
				$this->cat_type=$cat_type;
				$virtualCat=&$this->system->loadModel('goods/virtualcat');
				$vcat=$virtualCat->instance($cat_type);
				//print_r($vcat);exit;
				parse_str($vcat['filter'],$type_filter);
				 
			}
			
			
			$this->customer_template_type='gallery';
			$this->customer_template_id=$cat_id;

			$urlFilter=htmlspecialchars(urldecode($urlFilter));

			if($cat_id == '_ANY_'){
				unset($cat_id);
			}
			if($cat_id){
				$cat_id=explode(",",$cat_id);
				foreach($cat_id as $k=>$v){
					if($v) $cat_id[$k]=intval($v);
				}
				$this->id = implode(",",$cat_id);
			}
			if( !$cat_id  ){
				$cat_id = array('');
				$this->id = '';
			}
			//{{{初始化操作
			$pageLimit = $this->system->getConf('gallery.display.listnum');
			$this->pagedata['pdtPic']=array('width'=>100,'heigth'=>100);
		//        $orderBy = (!$orderBy)?3:$orderBy;
			$this->pagedata['args'] = array($this->id,urlencode($urlFilter),$orderBy,$tab,$page,$cat_type);
			$this->pagedata['curView'] = $view;
			$productCat = &$this->system->loadModel('goods/productCat');
			if($cat_type){
				$this->pagedata['childnode'] = $virtualCat->getCatParentById($cat_type,$view);
				
			}else{

				$this->pagedata['childnode'] = $productCat->getCatParentById($cat_id,$view);//获取商品分类
				//print_r($this->pagedata['childnode']);exit();
			}
			$brandGroup=&$this->system->loadModel('goods/brand');
			$objGoods = &$this->system->loadModel('goods/products');
			$brandResult=$brandGroup->getBrandGroup($cat_id);//获取商品分类
			 //print_r($brandResult);exit();
			$this->productCat = &$productCat;
			$cat = $productCat->get($cat_id,$view,$type_filter['type_id']);//对商品详细处理在相对应显示页面
			//error_log(print_r($cat,true),3,__FILE__.'.'.__FUNCTION__.'.cat.log');//alone add
			if( !in_array($view,$cat['setting']['list_tpl'])){
				header('Location: '.$this->system->mkUrl('gallery',current($cat['setting']['list_tpl']),$this->pagedata['args']),true,301);
			}

			if($cat_type){//商品分类的关键字
				$vcat['addon'] = unserialize($vcat['addon']);

				if(trim($vcat['addon']['meta']['keywords'])){
					 $this->keywords = trim($vcat['addon']['meta']['keywords']);
				}
				if(trim($vcat['addon']['meta']['description'])){
					$this->desc = trim($vcat['addon']['meta']['description']);
				}
				
				$this->title = ($vcat['addon']['meta']['title'])?trim($vcat['addon']['meta']['title']):$vcat['virtual_cat_name '];
				//if(trim($vcat['addon']['meta']['title'])){
				//    $this->title = trim($vcat['addon']['meta']['title']);
				//}
			  }else{
				if(trim($cat['addon'])){
					$cat['addon'] = unserialize($cat['addon']);
			  if(trim($cat['addon']['meta']['keywords'])){
						$this->keywords = trim($cat['addon']['meta']['keywords']);
					}
					if(trim($cat['addon']['meta']['description'])){
						$this->desc = trim($cat['addon']['meta']['description']);
					}
					 if(trim($cat['addon']['meta']['title'])){
						$this->title = trim($cat['addon']['meta']['title']);
					}
				}
			}

			if($this->system->getConf('system.seo.noindex_catalog'))//不索引目录页
				$this->header .= '<meta name="robots" content="noindex,noarchive,follow" />';

			$searchtools = &$this->system->loadModel('goods/search');
			$path =array();
			$filter = $searchtools->decode($urlFilter,$path,$cat);
			//error_log(print_r($filter,true),3,__FILE__.'.'.__FUNCTION__.'.filter.log');//alone add
			$this->filter = &$filter;
			/*if(!$cat_type){
				$this->title = $cat['cat_name'];
			}*/
			if(is_array($filter)){
				$filter=array_merge(array('cat_id'=>$cat_id,'marketable'=>'true'),$filter);
				if( ($filter['cat_id'][0] === '' || $filter['cat_id'][0] === null ) && !isset( $filter['cat_id'][1] ) )
					unset($filter['cat_id']);
				if( ($filter['tag'][0] === '' || $filter['tag'][0] === null ) && !isset( $filter['tag'][1] ) )
					unset($filter['tag']);
				if( ($filter['brand_id'][0] ==='' || $filter['brand_id'][0] === null) && !isset( $filter['brand_id'][1] ))
					unset($filter['brand_id']);
			}else{
				$filter = array('cat_id'=>$cat_id,'marketable'=>'true');
			}
			//--------获取类型关联的规格
			if ($vcat['type_id']){
				$type_id = $vcat['type_id'];
			}else{
				$type=$productCat->getFieldById($this->id,array('type_id'));
				$type_id=$type['type_id'];//获取相应“所属分类”的type_id
			}
			$gType = &$this->system->loadModel('goods/gtype');
			$SpecList = $gType->getSpec($type_id,1);//获取关联的规格
			//--------
			//error_log(print_r($path,true),3,__FILE__.'.'.__FUNCTION__.'.path.log');//alone add
			foreach($path as $p){
				$arg = unserialize(serialize($this->pagedata['args']));
		$arg[1] = $p['str'];
				$title = array();
				if(is_numeric($p['type'])){
					$cat_tmp = $productCat->get($cat_id,$view,$filter['type_id'][0]);
					foreach($p['data'] as $i){
						$name = $cat_tmp['props'][$p['type']]['options'][$i];
						$title[] = $name?$name:$i;
						$tip = $cat_tmp['props'][$p['type']]['name'];
					}
				}elseif($p['type']=='brand_id'){
					$brand = array();

					foreach($cat['brand'] as $b){
						$brand[$b['brand_id']] = $b['brand_name'];
					}
					foreach($p['data'] as $i){
						$title[] = $brand[$i];
						$tip = __("品牌");
					}
					unset($brand);
				}elseif(substr($p['type'],0,2)=='s_'){
					$spec = array();
					foreach($p['data'] as $spk => $spv){
						$tmp=explode(",",$spv);
						$tip = $SpecList[$tmp[0]]['name'];
						$title[]=$SpecList[$tmp[0]]['spec_value'][$tmp[1]]['spec_value'];
					}
					$curSpec[$tmp[0]]=$tmp[1];
				}
				$title = implode(',',$title);
				if($title){
					//$this->title=' '.$title;
					$this->path[] = array('title'=>" ".$title,'link'=>$this->system->mkUrl('gallery',$view,$arg),'tips'=>$tip);
				}
			}
			//-----------
			if($this->system->getConf('system.seo.noindex_catalog'))
				$this->header .= '<meta name="robots" content="noindex,noarchive,follow" />';

			$filter['cat_id'] = $cat_id;
			$filter['goods_type'] = 'normal';
			$filter['marketable'] = 'true';
			//-----查找当前类别子类别的关联类型ID
			if ($urlFilter){
				if($vcat['type_id']){
					//$filter['type_id']=$vcat['type_id'];
					$filter['type_id']=null;
					
				}
			}
			//--------
			$this->pagedata['tabs'] = $cat['tabs'];
			$this->pagedata['cat_id'] = implode(",",$cat_id);
			$this->pagedata['views'] = $cat['setting']['list_tpl'];//商品展示模式
			$this->pagedata['orderBy'] = $objGoods->orderBy();//排序方式
			if($cat['tabs'][$tab]){
				parse_str($cat['tabs'][$tab]['filter'],$_filter);
				$filter = array_merge($filter,$_filter);
			}
			if($GLOBALS['runtime']['member_lv']){
				$filter['mlevel'] = $GLOBALS['runtime']['member_lv'];
			}
			if(!isset($this->pagedata['orderBy'][$orderBy])){
				$this->system->error(404);
			}else{
				$orderby = $this->pagedata['orderBy'][$orderBy]['sql'];
			}

			foreach($brandResult as $v=>$k){
				$brand_count[$k['brand_id']]['plus']=$k['brand_cat'];
			}
			$selector = array();
			$search = array();

			if((!is_array($cat_id) && $cat_id) || $cat_id[0] || $cat_type){
				$goods_relate=$objGoods->getList("*",$filter,0,-1);
			}
			//error_log(print_r($goods_relate,true),3,__FILE__.'.'.__FUNCTION__.'.goods_relate.log');//alone add
			if ($goods_relate){
				unset($tmpSpecValue);
				foreach($goods_relate as $grk => $grv){
					if ($grv['spec_desc']){
						$tmpSdesc=unserialize($grv['spec_desc']);
						if(is_array($tmpSdesc)){
							foreach($tmpSdesc as $tsk => $tsv){
								foreach($tsv as $tk => $tv){
									if (!in_array($tv['spec_value_id'],$tmpSpecValue))
									$tmpSpecValue[]=$tv['spec_value_id'];
								}
							}
						}
					}
				}
			}
			/***********************/
			if ($SpecList){
				if ($curSpec)
					$curSpecKey=array_keys($curSpec);
				foreach($SpecList as $spk => $spv){
					$selected=0;
					/*
					$existsSV=0;
					foreach($spv['spec_value'] as $spvk => $spvv){
						if (!in_array($spvk,$tmpSpecValue))
							unset($spv['spec_value'][$spvk]);
						else
							$existsSV=1;
					}
					if ($existsSV){*/
						if ($curSpecKey&&in_array($spk,$curSpecKey)){
							$spv['spec_value'][$curSpec[$spk]]['selected']=true;
							$selected=1;
						}
						if ($spv['spec_style']=="select"){ //下拉
							$SpecSelList[$spk] = $spv;
							if ($selected)
								$SpecSelList[$spk]['selected'] = true;
						}
						elseif ($spv['spec_style']=="flat"){
							$SpecFlatList[$spk] = $spv;
							if ($selected)
								$SpecFlatList[$spk]['selected'] = true;
						}
					//}
				}
			}
			$this->pagedata['SpecFlatList'] = $SpecFlatList;
			$this->pagedata['specimagewidth'] = $this->system->getConf('spec.image.width');
			$this->pagedata['specimageheight'] = $this->system->getConf('spec.image.height');
			/************************/
			$selectorClass = array();
			//error_log(print_r($filter,true),3,__FILE__.'.'.__FUNCTION__.'.filter.log');//alone add
			if (is_array($cat['brand'])){
				foreach($cat['brand'] as $bk => $bv){
					$bCount=0;
					$brand = array('name'=>__('品牌'),'value'=>array_flip($filter['brand_id']));
					foreach($goods_relate as $gk => $gv){
						if ($gv['brand_id']){
							if ($gv['brand_id']==$bv['brand_id']){
								$bCount++;
							}
						}
					}
					if ($bCount>0){
						$tmpOp[$bv['brand_id']]=$bv['brand_name']."<span class='num'>(".$bCount.")</span>";
					}else{
						$tmpOp[$bv['brand_id']]=$bv['brand_name'];	//alone add
					}

					/* alone add start 选中的加亮 */
					if (in_array($bv['brand_id'],$filter['brand_id']))
					{
						$selectorClass['brand_id'][$bv['brand_id']]['addClass'] = true;
					}
					else $selectorClass['brand_id'][$bv['brand_id']]['addClass'] = false;
					/* alone add end */
				}
				$brand['options'] = $tmpOp;
				$selector['brand_id'] = $brand;
			}
			//error_log(print_r($filter,true),3,__FILE__.'.'.__FUNCTION__.'.filter.log');//alone add
			foreach($cat['props'] as $prop_id=>$prop){
				if($prop['search']=='select'){
					$prop['options'] = array_merge($prop['options']);
					$prop['value'] = $filter['p_'.$prop_id][0];
					$searchSelect[$prop_id] = $prop;
				}elseif($prop['search']=='input'){
					$prop['value'] = ($filter['p_'.$prop_id][0]);
					$searchInput[$prop_id] = $prop;
				}elseif($prop['search']=='nav'){
					$prop['value'] = array_flip($filter['p_'.$prop_id]);
					$plugadd=array();

					foreach($goods_relate as $k=>$v){

								if($v["p_".$prop_id]!=null){

									if($plugadd[$v["p_".$prop_id]]){
										$plugadd[$v["p_".$prop_id]]=$plugadd[$v["p_".$prop_id]]+1;
									}else{
										$plugadd[$v["p_".$prop_id]]=1;
									}
								}
						$aFilter['goods_id'][] = $v['goods_id'];    //当前的商品结果集
					}
					$navselector=0;
					foreach($prop['options'] as $q=>$e){
						if($plugadd[$q]){
							$prop['options'][$q]=$prop['options'][$q]."<span class='num'>(".$plugadd[$q].")</span>";
							if (!$navselector)
								$navselector=1;
						}else{
							//unset($prop['options'][$q]);	//alone remove
						}
						/* alone add start */
						if (in_array($q,$filter['p_'.$prop_id]))
						{
							$selectorClass[$prop_id][$q]['addClass'] = true;
						}
						else $selectorClass[$prop_id][$q]['addClass'] = false;
						/* alone add end */
					}
					$selector[$prop_id] = $prop;
				}
			}

			if ($navselector){
				$nsvcount=0;
				$noshow=0;
				foreach($selector as $sk => $sv){
					if ($sv['value']){
						$nsvcount++;
					}
					if (is_numeric($sk)&&!$sv['show']){
						$noshow++;
				}
				}
				if ($nsvcount==intval(count($selector)-$noshow))
					$navselector=0;
			}
			foreach($cat['spec'] as $spec_id=>$spec_name){
				$sId['spec_id'][] = $spec_id;
			}

			$cat['ordernum'] = $cat['ordernum']?$cat['ordernum']:array(''=>2);
			if ($cat['ordernum']){
				if ($selector){
					foreach($selector as $key => $val){
						if(!in_array($key,$cat['ordernum'])&&$val){
							$selectorExd[$key]=$val;
						}
					}
				}
			}

			$selector['ordernum'] = $cat['ordernum'];
			$objGoods->appendCols .= ',big_pic';/*appendCols big_pic update 2009年9月25日13:46:45*/
			if($type_filter['type_id'])$filter['type_id'][] = $type_filter['type_id'];
			$aProduct = $objGoods->getList('*',$filter,$pageLimit*($page-1),$pageLimit,$orderby);
			$count = $objGoods->count($filter);

			$this->pagedata['mask_webslice'] = $this->system->getConf('system.ui.webslice')?' hslice':null;
			$this->pagedata['searchInput'] = &$searchInput;
			$this->pagedata['selectorExd'] = $selectorExd;
			//alone add
			$this->pagedata['selectorClass'] = $selectorClass;
			$this->cat_id = $cat_id;
			$this->_plugins['function']['selector'] = array(&$this,'_selector');
			$this->pagedata['pager'] = array(
				'current'=>$page,
				'total'=>ceil($count/$pageLimit),
				'link'=>$this->system->mkUrl('gallery',$view,array(implode(',',$cat_id),urlencode($p['str']),$orderBy,$tab,($tmp = time()),$cat_type)),
				'token'=>$tmp);
			//error_log(var_export(urlencode($p['str']),true),3,"d:\text.txt");
			if($page != 1 && $page > $this->pagedata['pager']['total']){
				$this->system->error(404);
			}
			if(!$count){
				$this->pagedata['emtpy_info']=$this->system->getConf('errorpage.searchempty');
			}
			$objImage = &$this->system->loadModel('goods/gimage');
			$this->pagedata['searchtotal']=$count;
			if(is_array($aProduct) && count($aProduct) > 0){
			   
		$objGoods->getSparePrice($aProduct, $GLOBALS['runtime']['member_lv']);
				
		if($this->system->getConf('site.show_mark_price')){
					$setting['mktprice'] = $this->system->getConf('site.market_price');
				}else{
					$setting['mktprice'] =0;
				}
				$setting['saveprice'] = $this->system->getConf('site.save_price');
				$setting['buytarget'] = $this->system->getConf('site.buy.target');
				$this->pagedata['setting'] = $setting;
				$this->pagedata['products'] = &$aProduct;
			}
			if($GLOBALS['runtime']['member_lv']<0){
				$this->pagedata['LOGIN'] = 'nologin';
			}
			if($SpecSelList){
				$this->pagedata['SpecSelList'] = $SpecSelList;
			}
			if($searchSelect){
				$this->pagedata['searchSelect'] = &$searchSelect;
			}
			$this->pagedata['selector'] = &$selector;
			$this->pagedata['cat_type'] = $cat_type;

			$this->pagedata['search_array'] = implode("+",$GLOBALS['search_array']);//搜索的关键字
			if ($customView)
			{
				$cat['dftView'] = 'custom';
			}			
			$this->pagedata['_PDT_LST_TPL'] = dirname(__FILE__).'/view/shop/gallery/type/'.$cat['dftView'].'.html';
			$this->pagedata['_MAIN_'] = dirname(__FILE__).'/view/shop/gallery/index.html';
			$this->pagedata['selector_path'] = dirname(__FILE__).'/view/shop/gallery/selector/default.html';
			$this->pagedata['cat_prop'] = $cat['props'];
			$this->getGlobal($this->seoTag,$this->pagedata);
			//error_log(print_r($this->pagedata,true),3,__FILE__.'.'.__FUNCTION__.'.pagedata.log');//alone add
			//error_log(print_r($cat,true),3,__FILE__.'.'.__FUNCTION__.'.cat.log');//alone add
			$this->output();
		}

	}
?>